
import mqtt from 'mqtt';

function generateClientId(topic: string): string {
    return `${topic}-${Math.random().toString(36).substring(7)}`;
}
// 从环境变量中获取 MQTT 配置
const mqttUrl = import.meta.env.VITE_MQTT_URL;
const mqttUsername = import.meta.env.VITE_MQTT_CLIENT_NAME;
const mqttPassword = import.meta.env.VITE_MQTT_CLIENT_PASSWORD;

// 通用 MQTT 客户端设置函数
export function setupMqttClient(topic: string, onValid: (data: any) => void, clientId: string) {
    const client = mqtt.connect(mqttUrl, {
        clientId: clientId,
        username: mqttUsername,
        password: mqttPassword,
    });

    client.on('error', (err) => {
        console.error('MQTT 连接错误:', err);
    });

    client.on('connect', () => {
        mqttSubscribe(client, topic, (msg) => handleMqttMessage(topic, msg, onValid));
    });

    client.on('offline', () => {
        console.log(`MQTT 客户端 ${clientId} 已断开连接`);
    });

    return client;
}

// 通用处理消息的函数
export function handleMqttMessage(topic: string, msg: string, onValid: (data: any) => void) {
    try {
        const data = JSON.parse(msg);
        if (data) {
            onValid(data);
        }
    } catch (e) {
        console.error('解析消息失败:', e);
    }
}

// 通用订阅函数
export function mqttSubscribe(client: any, topic: string, callback: (message: string) => void) {
    client.subscribe(topic, (err?: Error) => {
        if (err) {
            console.error(`订阅主题失败: ${topic}`, err);
        } else {
            console.log(`已成功订阅主题: ${topic}`);
        }
    });

    client.on('message', (topic: string, message: Buffer) => {
        callback(message.toString());
    });
}

// 初始化 MQTT 客户端 两个主题
export function setupMqttClients(
    topicUpdate: string,
    topicEnd: string,
    onValidUpdate: (data: any) => void,
    onValidEnd: (data: any) => void
) {
    const client_Start = generateClientId(topicUpdate);
    const client_End = generateClientId(topicEnd);

    const mqttClientStart = setupMqttClient(topicUpdate, onValidUpdate, client_Start);
    const mqttClientEnd = setupMqttClient(topicEnd, onValidEnd, client_End);

    return { mqttClientStart, mqttClientEnd };
}
